/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.put.dcs.workManagerServer.classLoaders.jclClassLoaders;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.apache.log4j.Logger;
import xeus.jcl.JarClassLoader;

/**
 *
 * @author LukaszR
 */
public class ExtendJarLoader extends JarClassLoader
{

    public static Logger log = Logger.getLogger( ExtendJarLoader.class.getName() );

    @Override
    public InputStream getResourceAsStream( String path )
    {
        log.debug( "path to resource: " + path );
        // ladowanie resource. Zakldamy, ze to moze byc nawet zwykly plik
        byte[] ret = loadClassBytesForResource( path );
        // jezeli nic nie znaleziono, to probujemy przeksztalcic sciezke w format dla klas
        if ( ret == null )
        {

        }
        log.debug( "leght: " + ret.length );
        InputStream is = new ByteArrayInputStream( ret );
        return is;
    }

    /**
     * Potrzebne, jezeli chcemy zaladowac zwykly plik i nie chcemy  przeksztalcac nazwy
     * @param path
     * @return
     */
    protected byte[] loadClassBytesForResource( String path )
    {
        return super.loadClassBytes( path );
    }

    /**
     * Metoda przecizona, zeby dobrze dzialalo ladowanie klas
     * @param path
     * @return
     */
    @Override
    protected byte[] loadClassBytes( String path )
    {
        String tmpPath = formatClassNameForCreate( path );
        return super.loadClassBytes( tmpPath );
    }

    @Override
    protected String formatClassName( String path )
    {
        return path;
    }

    private String formatClassNameForCreate( String className )
    {
        char classNameReplacementChar = super.getClassNameReplacementChar();
        if ( classNameReplacementChar == '\u0000' )
        {
            // '/' is used to map the package to the path
            return className.replace( '.', '/' ) + ".class";
        }
        else
        {
            // Replace '.' with custom char, such as '_'
            return className.replace( '.', classNameReplacementChar ) + ".class";
        }
    }

    @Override
    public Class loadClass( String className ) throws ClassNotFoundException
    {
        log.debug( "Load class: " + className );
        return super.loadClass( className  );
    }
    
}
